from multiprocessing import Process
from sqlite3 import connect
import share
import config
from finance.finance import GFinance

TAG = 'Consumer:'

class Consumer(Process):
	PRICE_HIGHER = 'Current price %f is larger than your up bound %f!'
	PRICE_LOWER = 'Current price %f is lower than your down bound %f!'
	gfinance = GFinance()
	def __init__(self):
		Process.__init__(self)
		self.__conn = connect(config.DATABASE)
		self.__cur = self.__conn.cursor()
	def __del__(self):
		self.__cur.close()
	def run(self):
		while(True):
			#print self.pid
			scrb = share.GSR.get()
			print TAG, 'consumer with pid =', self.pid, 'get a scrb'
			uri = scrb[0] #uri which is used as dest for sending sms 
			stock_id = scrb[1]
			high_price = scrb[2]
			low_price = scrb[3]
			#high_mark = scrb[4]
			#low_mark = scrb[5]
			self.__monitor(uri, stock_id, high_price, low_price)
	 
	def __monitor(self, uri, stock_id, high_price, low_price):
		#finance handling and send sms info into global sms queue
		cur_price = Consumer.gfinance.get_stock_price(stock_id)
		high_price = float(high_price)
		low_price = float(low_price)
		cmd = 'select %s, %s from %s where %s=? and %s=?' %(config.HIGH_MARK, config.LOW_MARK, config.STOCK_TBL, config.FETION_URI, config.STOCK_ID)
		markset = self.__cur.execute(cmd, (uri, stock_id))
		marks = markset.fetchall()
		high_mark = marks[0][0]
		low_mark = marks[0][1]
		if cur_price >= high_price and high_mark:
			sms = Consumer.PRICE_HIGHER %(cur_price,high_price)
			cmd = 'update %s set %s=0 where %s=? and %s=?' %(config.STOCK_TBL, config.HIGH_MARK, config.FETION_URI, config.STOCK_ID)
			print TAG, 'process_id', self.pid, sms
			sms_req = (uri, sms)
			share.SMS_QUEUE.put(sms_req) #TODO: This may cause block if sms too much
			self.__cur.execute(cmd, (uri, stock_id))
			self.__conn.commit()
		elif cur_price < high_price and not high_mark:
			print TAG, 'high_mark reset true'
			cmd = 'update %s set %s=1 where %s=? and %s=?' %(config.STOCK_TBL, config.HIGH_MARK, config.FETION_URI, config.STOCK_ID)
			self.__cur.execute(cmd, (uri, stock_id))
			self.__conn.commit()
		elif cur_price <= low_price and low_mark:	
			sms = Consumer.PRICE_LOWER %(cur_price, low_price)
			cmd = 'update %s set %s=0 where %s=? and %s=?' %(config.STOCK_TBL, config.LOW_MARK, config.FETION_URI, config.STOCK_ID)
			print TAG, 'process_id', self.pid, sms
			sms_req = (uri, sms)
			share.SMS_QUEUE.put(sms_req) #TODO: This may cause block if sms too much
			self.__cur.execute(cmd, (uri, stock_id))
			self.__conn.commit()
		elif cur_price > low_price and not low_mark:
			print TAG, 'low_mark reset true'
			cmd = 'update %s set %s=1 where %s=? and %s=?' %(config.STOCK_TBL, config.LOW_MARK, config.FETION_URI, config.STOCK_ID)
			self.__cur.execute(cmd, (uri, stock_id))
			self.__conn.commit()
		else:
			pass

if __name__ == '__main__':
	pass
